package com.ideaaedi.springcloud.jd.message;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

import javax.annotation.Resource;
import java.util.Date;
import java.util.function.Consumer;

/**
 * 消息生产者 & 消息消费者 示例
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.5.A
 */
@Configuration
public class Demo implements ApplicationRunner {
    
    @Resource
    private StreamBridge streamBridge;
    
    /**
     * 消息生产者 发消息demo
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        boolean result = streamBridge.send("demoProducer-out-0",
                MessageBuilder.withPayload("我是消息~" + new Date())
                        .build());
        System.err.println("producer发送消息是否成功：" + result);
    }
    
    /**
     * 消息消费者demo
     */
    @Bean(value = "demoConsumer")
    public Consumer<Message<String>> provideDemoConsumer () {
        return new Consumer<Message<String>>() {
            @Override
            public void accept(Message<String> message) {
                String msg = message.getPayload();
                System.err.println("\nconsume接收到消息：\nmsg=" + msg + "\nheaders=" + message.getHeaders());
            }
        };
    }
}
